<template>
  <el-dialog v-model="dialogModel" title="配置AI大模型" width="40%" :modal="false">
    <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
      <el-form-item label="公开访问链接" prop="url">
        <el-input
          v-model="formData.url"
          placeholder="请输入AI大模型的公开访问链接"
          type="url"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogModel = false">取消</el-button>
      <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { updateAiMessage } from '@/db/index.js'
import { emitter } from '@/utils/eventBus'

const emit = defineEmits(['config-saved'])

const dialogModel = ref(false)
const loading = ref(false)
const formRules = reactive({
  url: [
    { required: true, message: '公开访问链接不能为空', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ]
})
const formRef = ref(null)
const formData = reactive({
  url: ''
})
const currentConversation = ref(null)

const open = (conversation) => {
  currentConversation.value = conversation

  // 重置表单
  formData.url = ''

  // 加载现有配置
  if (conversation.content && conversation.content.trim() !== '') {
    try {
      const parsedContent = JSON.parse(conversation.content)

      // 检查是否是正确的配置对象格式
      if (parsedContent && typeof parsedContent === 'object' && parsedContent.url) {
        formData.url = parsedContent.url
      }
      // 如果是旧的消息数组格式，保持空值
      else if (Array.isArray(parsedContent)) {
        console.log('检测到旧格式数据，使用空配置')
        formData.url = ''
      }
    } catch (e) {
      console.warn('解析配置失败:', e)
      formData.url = ''
    }
  }

  dialogModel.value = true
}

const submit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const config = {
      url: formData.url
    }

    await saveToDatabase(currentConversation.value.uuid, config)

    // 通知父组件配置已保存
    emit('config-saved', config)

    dialogModel.value = false
    ElMessage.success('配置保存成功')
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    loading.value = false
  }
}

const saveToDatabase = async (uuid, config) => {
  try {
    if (!uuid || !config) return

    const content = JSON.stringify(config)
    await updateAiMessage(uuid, content)

    // 通知导航更新预览
    emitter.emit('updateConversationPreview', { uuid, messages: config })
  } catch (error) {
    console.error('保存到数据库失败:', error)
    throw error
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.form-tip {
  margin-top: 4px;
}
</style>
